package com.joe.util;

import com.alibaba.druid.util.StringUtils;
import com.aliyuncs.utils.IOUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;
import com.google.gson.stream.JsonReader;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.*;

@Slf4j
public class GsonUtils {


    private static String pattern = "yyyy-MM-dd HH:mm:ss";
    private static Gson gson;

    static {
        gson = (new GsonBuilder()).setDateFormat(pattern).setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
    }

    public GsonUtils() {
    }

    public static <T> T jsonToEntity(String json, Class<T> cls) {
        return StringUtils.isEmpty(json) ? null : gson.fromJson(json, cls);
    }

    public static <T> T jsonToEntity(String json, Type type) {
        return StringUtils.isEmpty(json) ? null : gson.fromJson(json, type);
    }

    public static <T> List<T> jsonToList(String json, Class<T> cls) {
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            StringReader in = new StringReader(json);
            JsonReader read = new JsonReader(in);
            ArrayList list = new ArrayList();

            try {
                read.beginArray();

                while(read.hasNext()) {
                    T t = gson.fromJson(read, cls);
                    list.add(t);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
                freeResource(read);
            }

            return list;
        }
    }

    public static String objToJson(Object obj) {
        return gson.toJson(obj);
    }

    private static void freeResource(JsonReader read) {
        try {
            if (read != null) {
                read.close();
            }
        } catch (IOException var2) {
            var2.printStackTrace();
        }

    }



}
